#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowTitle("Server");
    resize(600,480);

    // 1.创建QTcpServer对象，用于监听连接
    m_tcpServer = new QTcpServer(this);

    // 3.连接信号
    connect(m_tcpServer, &QTcpServer::newConnection, this, &Widget::handld);

    // 2.监听客户端连接
    bool ret = m_tcpServer->listen(QHostAddress::Any, 8888);
    if(!ret){
        QMessageBox::critical(this, "Error", "failed listen");
        return;
    }

}

Widget::~Widget()
{
    delete ui;
}

void Widget::handld()
{
    // 4.得到通信的对象QTcpSocket
    QTcpSocket *clientSocket = m_tcpServer->nextPendingConnection();

    // 5.连接信号
    connect(clientSocket, &QTcpSocket::readyRead, [=]{
        ui->listWidget->addItem(">>> Client Connected...");

        // 接收来自客户端的数据
        QByteArray message = clientSocket->readAll();
        ui->listWidget->addItem(QString(">>> Server received message from Client：") + QString::fromUtf8(message));

        // 处理数据...

        // 将处理好的数据发回给客户端
        clientSocket->write(message);
        ui->listWidget->addItem(QString("<<< Server send message to Client：") + QString::fromUtf8(message));
    });

    // 6.连接信号
    connect(clientSocket, &QTcpSocket::disconnected, [=]{
        // 关闭监听对象
        m_tcpServer->close();
        // 清理数据
        clientSocket->deleteLater();
        // 关闭窗口
        close();
    });

}

